package com.ftd.daoImp;

import com.ftd.dao.BookDao;
import com.ftd.model.Book;
import com.ftd.model.Borrow;
import com.ftd.model.User;
import com.ftd.utils.HibernateUtil;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by apple on 2016/12/7.
 */
@Repository("BookDaoImp")

public class BookDaoImp extends BaseHibernateDaoImp  implements BookDao {

    Session session ;
    @Autowired
    Book book ;


    @Override
    public Book queryById(int id) {
        try{
            session = getSession();
            book = session.get(Book.class,id);

        } catch (Exception e){
            e.printStackTrace();
        } finally {
        }
        return book;
    }

    @Override
    public List<Book> queryAll() {
        List<Book> bookList = null;
        String hql;
        try{
            session = getSession();
            hql = "from Book";
            bookList  = session.createQuery(hql,Book.class).list();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
        }
        return bookList;
    }

    @Override
    public void insert(String bookName,int bookCount) {
        try{
            session = getSession();

            book = new Book.Builder(bookName).bookCount(bookCount).build();

            session.persist(book);
            session.getTransaction().commit();

        } catch (Exception e){
            e.printStackTrace();
        } finally {
        }

    }

    @Override
    public void updateBookByIdAndCount(int id , int count) {

        try {
            session = getSession();
            book = queryById(id);
            book.setBookCount(book.getBookCount()+count);
            session.persist(book);
//            session.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

    }

    @Override
    public void delete(int id) {

    }

    @Override
    public void closeSession(){
        HibernateUtil.closeSession();
    }
}
